import {
  CloseOutlined,
  CommentOutlined,
  CopyOutlined,
  EditOutlined,
  SyncOutlined,
  UserOutlined,
  HeartOutlined,
  QrcodeOutlined,
  RocketOutlined,
  DownloadOutlined
} from "@ant-design/icons"
import { Bubble, Sender } from "@ant-design/x"
import type { BubbleProps } from "@ant-design/x"
import {
  Button,
  Card,
  Col,
  FloatButton,
  Layout,
  Menu,
  message,
  Modal,
  Row,
  Space,
  theme,
  Tooltip,
  Typography,
  Skeleton,
  type GetRef
} from "antd"
import markdownit from "markdown-it"
import { useEffect, useLayoutEffect, useRef, useState } from "react"
import { admin } from "./api/index"

import styles from "./options.module.scss"
import { cssStringToObject } from "./utils"

const { Header, Content, Footer } = Layout
const { Title } = Typography

export default function LayoutComponent({
  children
}: {
  children: React.ReactNode
}) {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [inputMessage, setInputMessage] = useState("")
  const [conversation, setConversation] = useState<
    Array<{ role: string; content: string }>
  >([])
  const [isLoading, setIsLoading] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const portRef = useRef<chrome.runtime.Port | null>(null)
  const [isDone, setIsDone] = useState(false)
  const [showLoading, setShowLoading] = useState(false)
  const [websites, setWebsites] = useState([])
  const [currentWebsite, setCurrentWebsite] = useState<string | null>(null)
  const [showWebsiteContainer, setShowWebsiteContainer] = useState(false)
  const senderRef = useRef<GetRef<typeof Sender>>(null)
  const [isRewardModalOpen, setIsRewardModalOpen] = useState(false)
  const [headerStyle, setHeaderStyle] = useState({})
  const [webLoading, setWebLoading] = useState(true)
  const [categories, setCategories] = useState([]) // 存储分类
  const [selectedCategory, setSelectedCategory] = useState(null) // 选中的分类
  const [updateInfo, setUpdateInfo] = useState(null); // 存储更新信息
  const [isUpdateModalVisible, setIsUpdateModalVisible] = useState(false); // 新增更新模态框状态
  const [isDownloading, setIsDownloading] = useState(false)  // 更新包下载状态

  useEffect(() => {
    getWebLists();
    getConfig();
  }, []);

  useEffect(() => {
    chrome.runtime.onMessage.addListener((message) => {
      if (message.action === "SHOW_UPDATE_NOTIFICATION") {
        setUpdateInfo(message.updateInfo);
        setIsUpdateModalVisible(true); // 标记模态框已显示
      }
    });
  }, [isUpdateModalVisible]);

  const handleUpdate = () => {
      const downloadUrl = updateInfo.download_url
      if (downloadUrl) {
        const filename = 'Browser Tools ' + updateInfo.version + '.zip';

        // 通知 background.ts 停止更新检查
        chrome.runtime.sendMessage({
          action: "STOP_UPDATE_CHECK"
        }).catch(error => {
          console.log("发送停止更新检查消息失败:", error);
        });
        
        // 显示下载中状态
        setIsDownloading(true);
        
        fetch(downloadUrl)
          .then(response => {
            if (!response.ok) {
              throw new Error('下载失败: ' + response.status);
            }
            return response.blob();
          })
          .then(blob => {
            // 创建 blob URL（同源的）
            const blobUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = blobUrl;
            link.download = filename;
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 清理 blob URL
            setTimeout(() => {
              window.URL.revokeObjectURL(blobUrl);
            }, 100);
            
            // 关闭模态框
            setUpdateInfo(null);
            setIsUpdateModalVisible(false);
          })
          .catch(error => {
            console.error('下载失败:', error);
            // 降级方案：直接打开链接
            window.open(downloadUrl, '_blank');
          })
          .finally(() => {
            setIsDownloading(false);
          });
      }
  };
  
  // 修改取消按钮的处理函数
  const handleCancelUpdate = () => {
    setUpdateInfo(null);
    setIsUpdateModalVisible(false); // 重置显示状态
  };

  // 获取常用网站
  const getWebLists = () => {
    admin
    .webList()
    .then(res => {
        setWebsites(res.data);
        setWebLoading(false);
        
        // 处理分类数据
        const uniqueCategories = [];
        const categoryMap = new Map();
        
        res.data.forEach(website => {
          if (!categoryMap.has(website.type)) {
            categoryMap.set(website.type, website.typeText);
            uniqueCategories.push({
              type: website.type,
              typeText: website.typeText
            });
          }
        });
        
        setCategories(uniqueCategories);
        
        // 默认选择第一个分类
        if (uniqueCategories.length > 0) {
          setSelectedCategory(uniqueCategories[0].type);
        }
    })
    .catch(error => {
      console.error("获取网站列表失败:", error);
      setWebLoading(false);
    });
  };

  // 获取当前选中分类的网站
  const getWebsitesByCategory = () => {
    if (!selectedCategory) return [];
    const filteredWebsites = websites.filter(website => website.type === selectedCategory);
    return filteredWebsites;
  };

  // 获取配置参数
  const getConfig = () => {
    admin
      .getConfig({})
      .then(res => {
        // 获取头部样式
        // let style = res.data.find((item) => item.modal === "header.styles")
        // let styleParams = style.params;
        // let styleObject = cssStringToObject(styleParams);
        // setHeaderStyle(styleObject);
      });
  };

  // 新增：处理打赏按钮点击
  const handleRewardClick = () => {
    setIsRewardModalOpen(true)
  }

  // 新增：关闭打赏模态框
  const handleRewardCancel = () => {
    setIsRewardModalOpen(false)
  }

  const openWebsite = (url: string) => {
    setCurrentWebsite(url)
    setShowWebsiteContainer(true)
  }

  const closeWebsiteContainer = () => {
    setShowWebsiteContainer(false)
    setCurrentWebsite(null)
  }

  useEffect(() => {
    document.documentElement.style.overflow = "hidden"
    return () => {
      document.documentElement.style.overflow = ""
      if (portRef.current) {
        portRef.current.disconnect()
      }
    }
  }, [])

  useEffect(() => {
    return () => {
      const ports = chrome.runtime.connect && chrome.runtime.connect()
      if (ports) {
        ports.disconnect()
      }
    }
  }, [])

  // 自动滚动到底部
  useLayoutEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" })
    }
  }, [conversation])

  const { token } = theme.useToken()
  const onCopy = (textToCopy: any) => {
    if (!textToCopy) return message.warning("没有可复制的内容")
    navigator.clipboard
      .writeText(textToCopy)
      .then(() => {
        message.success("复制成功")
      })
      .catch((err) => {
        console.error("复制失败:", err)
      })
  }

  // 修改按钮
  const handleEditMessage = (content: string) => {
    setInputMessage(content)
    // 自动聚焦到输入框
    senderRef.current!.focus({
      cursor: "end"
    })
  }

  // 处理重新生成按钮点击
  const handleRegenerate = async () => {
    if (conversation.length === 0 || isLoading) return

    // 找到最后一条用户消息
    const lastUserMessageIndex = conversation.findLastIndex(
      (msg) => msg.role === "user"
    )
    if (lastUserMessageIndex === -1) return

    // 移除最后一条AI消息（如果有）
    setConversation((prev) => {
      const newConversation = [...prev]
      // 如果最后一条是AI消息，则移除
      if (newConversation[newConversation.length - 1]?.role === "assistant") {
        newConversation.pop()
      }
      return newConversation
    })

    setIsLoading(true)
    setIsDone(false)
    setShowLoading(true)

    const timeoutId = setTimeout(() => {
      setIsLoading(false)
    }, 30000)

    try {
      await new Promise<void>((resolve, reject) => {
        const port = chrome.runtime.connect({ name: "deepseek-stream" })
        portRef.current = port

        port.onDisconnect.addListener(() => {
          if (chrome.runtime.lastError) {
            console.error("端口连接错误:", chrome.runtime.lastError)
            reject(chrome.runtime.lastError)
          }
          clearTimeout(timeoutId)
          setIsLoading(false)
        })

        let aiResponse = ""
        port.onMessage.addListener((msg) => {
          if (msg.chunk) {
            setShowLoading(false)
            aiResponse += msg.chunk
            setConversation((prev) => {
              const lastMessage = prev[prev.length - 1]
              if (lastMessage?.role === "assistant") {
                lastMessage.content = aiResponse
                return [...prev]
              } else {
                return [...prev, { role: "assistant", content: aiResponse }]
              }
            })
          }

          if (msg.done && !msg.error) {
            clearTimeout(timeoutId)
            setIsLoading(false)
            setIsDone(true)
            port.disconnect()
            resolve()
          }

          if (msg.error) {
            clearTimeout(timeoutId)
            setIsLoading(false)
            setConversation((prev) => {
              const newConversation = [...prev]
              const lastMessage = newConversation[newConversation.length - 1]
              if (lastMessage.role === "assistant") {
                lastMessage.content = msg.error
              }
              return newConversation
            })
            message.error(msg.error)
            port.disconnect()
            reject(msg.error)
          }
        })

        // 发送请求，使用到最后一个用户消息为止的对话历史
        const messagesToSend = conversation.slice(0, lastUserMessageIndex + 1)
        port.postMessage({
          action: "callDeepSeekAIStream",
          messages: messagesToSend
        })
      })
    } catch (error) {
      console.error("AI调用失败:", error)
      setIsLoading(false)
    }
  }

  const handleAbort = () => {
    if (portRef.current) {
      portRef.current.disconnect()
      portRef.current = null
    }
    setIsLoading(false)
    message.info("已停止生成")
    // 将最后一条AI消息设置为当前累积的内容
    setConversation((prev) => {
      const lastMessage = prev[prev.length - 1]
      if (lastMessage.role === "assistant") {
        return prev
      }
      return [...prev, { role: "assistant", content: "已停止生成" }]
    })
  }

  const handleAiChat = async () => {
    if (!inputMessage.trim()) {
      message.warning("请输入消息内容")
      return
    }

    setIsLoading(true)
    setIsDone(false)
    setShowLoading(true)

    // 先添加用户消息
    const userMessage = { role: "user", content: inputMessage }
    setConversation((prev) => [...prev, userMessage])
    setInputMessage("")

    const timeoutId = setTimeout(() => {
      setIsLoading(false)
    }, 30000)

    try {
      await new Promise<void>((resolve, reject) => {
        const port = chrome.runtime.connect({ name: "deepseek-stream" })
        portRef.current = port

        port.onDisconnect.addListener(() => {
          if (chrome.runtime.lastError) {
            console.error("端口连接错误:", chrome.runtime.lastError)
            reject(chrome.runtime.lastError)
          }
          clearTimeout(timeoutId)
          setIsLoading(false)
        })

        let aiResponse = ""
        port.onMessage.addListener((msg) => {
          if (msg.chunk) {
            setShowLoading(false)
            aiResponse += msg.chunk
            // 只有当AI消息不存在时才创建，否则更新内容
            setConversation((prev) => {
              const lastMessage = prev[prev.length - 1]
              if (lastMessage?.role === "assistant") {
                lastMessage.content = aiResponse
                return [...prev]
              } else {
                return [...prev, { role: "assistant", content: aiResponse }]
              }
            })
          }

          if (msg.done && !msg.error) {
            clearTimeout(timeoutId)
            setIsLoading(false)
            setIsDone(true)
            port.disconnect()
            resolve()
          }

          if (msg.error) {
            clearTimeout(timeoutId)
            setIsLoading(false)
            setConversation((prev) => {
              const newConversation = [...prev]
              const lastMessage = newConversation[newConversation.length - 1]
              if (lastMessage.role === "assistant") {
                lastMessage.content = msg.error
              }
              return newConversation
            })
            message.error(msg.error)
            port.disconnect()
            reject(msg.error)
          }
        })

        // 发送请求
        port.postMessage({
          action: "callDeepSeekAIStream",
          messages: [...conversation, userMessage]
        })
      })
    } catch (error) {
      console.error("AI调用失败:", error)
      setIsLoading(false)
    }
  }

  const showModal = () => {
    setIsModalOpen(true)
    // 初始化系统消息
    if (conversation.length === 0) {
      setConversation([{ role: "system", content: "你是一个乐于助人的助手" }])
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const barAvatar: React.CSSProperties = {
    color: "#fff",
    backgroundColor: "#87d068"
  }
  const fooAvatar: React.CSSProperties = {
    color: "#f56a00",
    backgroundColor: "#fde3cf"
  }
  const hideAvatar: React.CSSProperties = {
    visibility: "hidden"
  }
  // Ai文本内容样式
  const aiContentCss: React.CSSProperties = {
    padding: "0 16px",
    background: "#fde3cf"
  }
  // 用户文本内容样式
  const userContentCss: React.CSSProperties = {
    padding: "0 16px",
    background: "#87d068"
  }
  // 文本底部按钮样式
  const btnFooter: React.CSSProperties = {
    padding: "0",
    margin: "0",
    marginBottom: "10px"
  }

  const md = markdownit({ html: true, breaks: true })
  const renderMarkdown: BubbleProps["messageRender"] = (content) => {
    return (
      <Typography>
        <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
      </Typography>
    )
  }

  return (
    <Layout className={styles.layoutContainer}>
      {/* 悬浮按钮 */}
      <FloatButton
        onClick={showModal}
        icon={<CommentOutlined />}
        tooltip="AI助手"
      />

      {/* 更新提示弹窗 */}
      {updateInfo && (
        <Modal
          title={null}
          footer={null}
          open={!!updateInfo}
          width={520}
          closable={false}
          maskClosable={false}
          className="update-modal"
          styles={{
            body: { padding: 0 }
          }}
        >
          <div style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', padding: '10px', textAlign: 'center', borderRadius: '10px' }}>
            <Space direction="vertical" size="middle">
              <RocketOutlined style={{ fontSize: '48px', color: 'white' }} />
              <Title level={5} style={{ color: 'white', margin: 0 }}>
                发现新版本：{updateInfo?.version}
              </Title>
            </Space>
          </div>

          <div style={{ padding: '5px 10px' }}>
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              {/* 更新内容 */}
              <div>
                <Title level={5} style={{ marginBottom: '12px' }}>
                  🎉 更新内容
                </Title>
                <Card 
                  size="small" 
                  style={{ backgroundColor: '#fafafa', maxHeight: '200px', overflow: 'auto' }}
                >
                  {updateInfo?.update_log ? (
                    <div dangerouslySetInnerHTML={{ 
                      __html: md.render(updateInfo.update_log) 
                    }} />
                  ) : (
                    <span>暂无更新说明</span>
                  )}
                </Card>
              </div>

              {/* 操作按钮 */}
              <Space size="middle" style={{ width: '100%', justifyContent: 'center' }}>
                <Button 
                  type="primary" 
                  size="large"
                  icon={<DownloadOutlined />}
                  loading={isDownloading}
                  onClick={handleUpdate}
                  style={{
                    background: '#1677ff',
                    border: 'none',
                    borderRadius: '6px',
                    padding: '0 24px',
                    height: '40px'
                  }}
                >
                  立即更新
                </Button>
                <Button 
                  size="large"
                  onClick={handleCancelUpdate}
                  style={{
                    borderRadius: '6px',
                    padding: '0 24px',
                    height: '40px'
                  }}
                >
                  稍后再说
                </Button>
              </Space>
            </Space>
          </div>
        </Modal>
      )}

      {/* AI 对话框 */}
      <Modal
        title="AI 助手"
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
        width={800}
        closeIcon={<CloseOutlined />}
        styles={{
          body: {
            padding: 0,
            height: "500px",
            display: "flex",
            flexDirection: "column",
            backgroundColor: "#f9f9f9"
          }
        }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            height: "100%",
            overflow: "hidden",
            backgroundColor: "#f9f9f9"
          }}>
          {/* 对话历史区域 - 固定高度并滚动 */}
          <div
            style={{
              flex: 1,
              padding: "16px",
              overflowY: "auto",
              backgroundColor: "#f9f9f9",
              minHeight: 0
            }}>
            {conversation
              .filter((msg) => msg.role !== "system")
              .map((message, index) => (
                <div key={index}>
                  {message.role === "assistant" && (
                    <Bubble
                      key={index}
                      avatar={{ icon: <UserOutlined />, style: fooAvatar }}
                      placement={"start"}
                      typing={index === conversation.length - 1 && isLoading}
                      styles={{ content: aiContentCss, footer: btnFooter }}
                      content={message.content}
                      messageRender={renderMarkdown}
                      footer={(messageContext) => (
                        <Space size={token.paddingXXS}>
                          <Tooltip title="复制">
                            <Button
                              color="default"
                              variant="text"
                              size="small"
                              onClick={() => onCopy(messageContext)}
                              icon={<CopyOutlined />}
                            />
                          </Tooltip>
                          {index === conversation.length - 2 && (
                            <Tooltip title="重新生成">
                              <Button
                                color="default"
                                variant="text"
                                size="small"
                                onClick={() => handleRegenerate()}
                                icon={<SyncOutlined />}
                              />
                            </Tooltip>
                          )}
                        </Space>
                      )}
                    />
                  )}
                  {message.role === "user" && (
                    <Bubble
                      key={index}
                      avatar={{ icon: <UserOutlined />, style: barAvatar }}
                      placement={"end"}
                      styles={{ content: userContentCss, footer: btnFooter }}
                      content={message.content}
                      messageRender={renderMarkdown}
                      footer={(messageContext) => (
                        <Space size={token.paddingXXS}>
                          <Tooltip title="复制">
                            <Button
                              color="default"
                              variant="text"
                              size="small"
                              onClick={() => onCopy(messageContext)}
                              icon={<CopyOutlined />}
                            />
                          </Tooltip>
                          {index === conversation.length - 3 && (
                            <Tooltip title="修改">
                              <Button
                                color="default"
                                variant="text"
                                size="small"
                                onClick={() =>
                                  handleEditMessage(messageContext)
                                }
                                icon={<EditOutlined />}
                              />
                            </Tooltip>
                          )}
                        </Space>
                      )}
                    />
                  )}
                </div>
              ))}
            {/* 显示Loading状态 */}
            {showLoading && (
              <Bubble
                avatar={{ icon: <UserOutlined />, style: fooAvatar }}
                placement="start"
                loading={true}
                typing={true}
                content=""
                styles={{ content: aiContentCss }}
              />
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 - 固定高度 */}
          <div
            style={{
              padding: "10px 10px 0 10px",
              borderTop: "1px solid #e8e8e8",
              backgroundColor: "white",
              flexShrink: 0
            }}>
            <Sender
              loading={isLoading}
              value={inputMessage}
              onChange={(v) => {
                setInputMessage(v)
              }}
              onSubmit={() => {
                setInputMessage("")
                setIsLoading(true)
                handleAiChat()
              }}
              onCancel={() => {
                setIsLoading(false)
                setShowLoading(false)
                handleAbort()
              }}
              ref={senderRef}
              placeholder="请输入您的问题，并按Enter发送，按Shift + Enter换行"
              autoSize={{ minRows: 2, maxRows: 6 }}
            />
          </div>
          <div
            style={{
              color: "#a3a3a3",
              textAlign: "center",
              fontSize: "12px",
              paddingLeft: "10px",
              backgroundColor: "#fff"
            }}>
            内容由AI生成，无法确保真实准确，仅供参考
          </div>
        </div>
      </Modal>

      {/* 打赏模态框 */}
      <Modal
        title="支持开发者"
        open={isRewardModalOpen}
        onCancel={handleRewardCancel}
        footer={null}
        width={400}
        closeIcon={<CloseOutlined />}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <p style={{ marginBottom: '20px' }}>感谢您的支持！扫描二维码打赏开发者</p>
          <div style={{ 
            width: '250px', 
            height: '250px', 
            margin: '0 auto',
            backgroundColor: '#f5f5f5',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            border: '1px dashed #d9d9d9'
          }}>
            {/* 这里放置您的二维码图片 */}
            <QrcodeOutlined style={{ fontSize: '64px', color: '#1890ff' }} />
            <span style={{ marginLeft: '8px' }}>二维码占位</span>
          </div>
          <p style={{ marginTop: '20px', color: '#999', fontSize: '12px' }}>
            扫描上方二维码，任意金额都是对开发者的鼓励
          </p>
        </div>
      </Modal>

      {/* 顶部导航 */}
      <Header className={styles.header} style={headerStyle}>
        <Space style={{ width: "100%", justifyContent: "space-between", flexWrap: "wrap" }}>
          <Title level={3} style={{ color: "white", margin: 0, minWidth: "120px" }}>
            Brower Tools
          </Title>
          <div style={{ 
            display: 'flex', 
            justifyContent: 'flex-end', 
            alignItems: 'center',
            minWidth: "150px"
          }}>
            <Button type="primary" size="middle" icon={<HeartOutlined />} onClick={handleRewardClick}>
              打赏
            </Button>
          </div>
        </Space>
      </Header>

      <Layout>
        <Content className={styles.mainContent}>
          <div className={styles.content}>
            <Row>
              <Col span={18} push={6} style={{ height: "100%" }}>
                {showWebsiteContainer && currentWebsite ? (
                  <div
                    style={{
                      height: "780px",
                      display: "flex",
                      flexDirection: "column"
                    }}>
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        marginBottom: "10px",
                        padding: "10px",
                        backgroundColor: "#f0f0f0",
                        borderRadius: "4px"
                      }}>
                      <div
                        style={{
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                          maxWidth: "80%"
                        }}>
                        {currentWebsite}
                      </div>
                      <Button
                        type="primary"
                        danger
                        size="small"
                        onClick={closeWebsiteContainer}>
                        关闭
                      </Button>
                    </div>
                    <iframe
                      src={currentWebsite}
                      style={{
                        flex: 1,
                        width: "100%",
                        border: "1px solid #ddd",
                        borderRadius: "4px"
                      }}
                      title="website-container"
                    />
                  </div>
                ) : (
                  <div>
                    <Skeleton loading={webLoading}>
                      <div
                        style={{
                          display: "grid",
                          gridTemplateColumns:
                            "repeat(auto-fill, minmax(200px, 1fr))",
                          gap: "16px",
                          marginTop: "16px"
                        }}>
                        {getWebsitesByCategory().map((website) => (
                          <Card
                            key={website.id}
                            hoverable
                            style={{ cursor: "pointer",width: '180px',padding: '6px', marginLeft: '10px' }}
                            onClick={() => openWebsite(website.path)}
                          >
                            <div style={{display:'flex',alignItems:'center',justifyContent:'flex-start',gap: '8px'}}>
                              <img src={website.thumb} alt="" style={{width: "25px",height: "25px",flexShrink: 0}}/>
                              <div
                                title={website.path}
                                style={{
                                  fontSize: "16px",
                                  fontWeight: "500",
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                  flex: 1
                                }}>
                                {website.name}
                              </div>
                            </div>
                          </Card>
                        ))}
                      </div>
                    </Skeleton>
                  </div>
                )}
              </Col>
              <Col
                span={6}
                pull={18}
                style={{
                  alignItems: "center",
                  justifyContent: "center",
                  display: "flex"
                }}>
                <Card title="分类" style={{ width: 400, margin: "30px auto" }}>
                  {categories.map(category => (
                    <div 
                      key={category.type}
                      style={{
                        padding: "8px 12px",
                        margin: "4px 0",
                        borderRadius: "4px",
                        cursor: "pointer",
                        backgroundColor: selectedCategory === category.type ? "#e6f7ff" : "transparent",
                        border: selectedCategory === category.type ? "1px solid #91d5ff" : "1px solid #f0f0f0"
                      }}
                      onClick={() => setSelectedCategory(category.type)}
                    >
                      {category.typeText}
                    </div>
                  ))}
                </Card>
              </Col>
            </Row>
          </div>
        </Content>
      </Layout>

      <Footer className={styles.footer}>
        Brower Tools © 2025 | 当前扩展版本 {chrome.runtime.getManifest().version}
      </Footer>
    </Layout>
  )
}